package main

import (
	"fmt"
	"sync"
	"time"
)

var (
	mLock sync.Mutex
	cond  = sync.NewCond(&mLock)
	queue []int
)

func producer() {
	for i := 1; i <= 5; i++ {
		mLock.Lock()
		queue = append(queue, i)
		fmt.Println("Produced:", i)
		cond.Signal() // 唤醒等待的消费者
		mLock.Unlock()
		time.Sleep(time.Millisecond * 500)
	}
}

func consumer() {
	for i := 0; i < 5; i++ {
		mLock.Lock()
		for len(queue) == 0 {
			cond.Wait() // 等待生产者信号
		}
		item := queue[0]
		queue = queue[1:]
		fmt.Println("Consumed:", item)
		mLock.Unlock()
	}
}

func main() {
	go producer()
	go consumer()
	time.Sleep(time.Second * 3)
	fmt.Println("All thread is over!")
}
